package cn.damong.interceptor;

import java.lang.reflect.Method;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.damong.annotation.WeixinAuthorization;


/**
 * <p>微信授权拦截器，拦截注解{@link cn.damong.annotation.WeixinAuthorization}标记的页面。
 * 如果用户端cookie中不包含ukey，或者ukey不合法，则跳转到用户授权页面，用户授权后跳转回原先的页面
 * </p>
 * 
 * @author CodingPanda
 * @2019年5月15日 下午9:43:53
 *
 */
@Component
public class WeixinAuthorizationInterceptor extends HandlerInterceptorAdapter {
	private Logger logger = LoggerFactory.getLogger(WeixinAuthorizationInterceptor.class);

	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		/**
		 *  如果不是映射到方法直接通过
		 */
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
		
		/**
		 * 如果没有WeixinAuthorization注解，跳过
		 */
		HandlerMethod hm = (HandlerMethod) handler;
		Method method = hm.getMethod();
		if (!(method.isAnnotationPresent(WeixinAuthorization.class))) {
			return true;
		}
		
		/**
		 * 从cookie中获取ukey, ukey即用户的openid
		 */
		String openid = null;
		Cookie[] cookies = request.getCookies();
		if (cookies != null && cookies.length != 0) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equalsIgnoreCase("ukey")) {
					openid = cookie.getValue();
				}
			}
		}
		
		/**
		 * 如果openid为空，则跳转到授权页面，并保证授权后跳转回当前页面
		 */
		if (StringUtils.isBlank(openid)) {
			String url = request.getServletPath();
			
			String queryString = request.getQueryString();
			if(StringUtils.isNotBlank(queryString)) {
				url += "?" + queryString;
			}
			 
			WeixinAuthorization auth = method.getAnnotation(WeixinAuthorization.class);
			url = URLEncoder.encode(url, "utf-8");
			String targetUrl = "/weixin/auth?authType=" + auth.authType();
			response.sendRedirect("/redirect/?callBackUrl=" + url + "&targetUrl=" + targetUrl);
			return false;
		} else {
			return true;
		}
	}
	
}
